<?php
include_once 'Singleton.php';
//if(!defined("LOGIN_TIMEOUT")) define("LOGIN_TIMEOUT", 600);
if(!defined("SESSION_NAME")) define("SESSION_NAME", "mt_session");

/*
 * Class Session provides a simple interface to register a session for a user.
 */
 
class Session extends Singleton
{
  
  protected function Session()
  {
    if(!isset($_SESSION))
    {
      session_name(SESSION_NAME);
      session_start();  
    }  
  }
  
  public static function &factory()
  {
    return parent::getSingleton(__CLASS__);
  }
  
  public function login($fb_id)
  {
    $mysql = SQL::factory();
        
    $query = "SELECT id FROM mt_user
              WHERE fb_id = '$fb_id'";
    
    $mysql->query($query);
    
    if($mysql->numRows() > 0)
    {
      if($mysql->numRows() > 1)
        throw MTException('More than one user with the same facebook id');
        
      $_SESSION[userId] = $mysql->query($query)->fetchObject()->id;
      return true;
    }
    
    return false;
  }
  
  public function logout()
  {
    session_regenerate_id();
    
    unset($_SESSION[userId]);
  }
  
  public function isLogged()
  {
    return isset($_SESSION["userId"]);
  }
   
  /*
  * use this function whenever you
  * need a session token to control
  * the flow of your operations (see registration for an example).
  * Note that using tokens prevents from brute force attack by bots.
  */
  
  public function generateToken(){
     $_SESSION[token] = bin2hex(md5(uniqid(rand(),1), true));
     return $_SESSION[token];
  }
  
  public function getUserId()
  {
    return $_SESSION[userId];
  }  
}

?>
